﻿using System;
using System.Collections.Generic;
using System.Management;

namespace Module_Debug
{
    class Detection
    {
        // usb消息定义
        public class UsbSet
        {
            public const int WM_DEVICE_CHANGE = 0x219;
            public const int DBT_DEVICEARRIVAL = 0x8000;
            public const int DBT_DEVICE_REMOVE_COMPLETE = 0x8004;
            public const UInt32 DBT_DEVTYP_PORT = 0x00000003;
        }


        /// <summary>
        /// Get the system devices information with windows api.
        /// </summary>
        /// <param name="hardType">Device type.</param>
        /// <param name="propKey">the property of the device.</param>
        /// <returns></returns>
        private static string[] GetHarewareInfo(SerialPortManager.HardwareEnum hardType, string propKey)
        {
            List<string> strs = new List<string>();
            try
            {
                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + hardType))
                {
                    var hardInfos = searcher.Get();
                    foreach (var hardInfo in hardInfos)
                    {
                        if (hardInfo.Properties[propKey].Value != null)
                        {
                            String str = hardInfo.Properties[propKey].Value.ToString();
                            strs.Add(str);
                        }
                    }
                }
                return strs.ToArray();
            }
            catch
            {
                return null;
            }
            finally
            {
                strs = null;
            }
        }

        /// <summary>
        /// Get the target com num.
        /// </summary>
        /// <returns></returns>
        public static string GetComNum()
        {
            string comNum = null;
            string[] portNames = SerialPortManager.MulGetHardwareInfo(SerialPortManager.HardwareEnum.Win32_SerialPort, "Name");

            foreach (string s in portNames)
            {
                if (s.Length >= 23 && s.Contains("STMic"))
                {
                    int start = s.IndexOf("(");
                    int end = s.IndexOf(")");
                    comNum = s.Substring(start + 1, end - start - 1);
                }
                else if (s.Length >= 5 && s.Contains("USB") && s.Contains("串行设备"))
                {
                    int start = s.IndexOf("(");
                    int end = s.IndexOf(")");
                    comNum = s.Substring(start + 1, end - start - 1);
                }
            }
            return comNum;
        }

    }
}
